package ua.kharkov.knure.mikhaylov.st4.web.command;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.mikhaylov.st4.db.entities.Account;
import ua.kharkov.knure.mikhaylov.st4.db.entities.User;
import ua.kharkov.knure.mikhaylov.st4.db.management.DBManager;
import ua.kharkov.knure.mikhaylov.st4.settings.LocaleData;
import ua.kharkov.knure.mikhaylov.st4.settings.Path;

/**
 * Command - refills the account
 * 
 * @author Saint
 * 
 */
public class RefillAccountCommand extends Command {

	private static final long serialVersionUID = 3854817278661996409L;
	private static final Logger log = Logger
			.getLogger(RefillAccountCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		log.debug("Command starts");

		log.trace("Checking parameters");

		User user = (User) request.getSession().getAttribute("user");

		Long id = 0L;
		Double value = 0.;
		try {
			id = Long.valueOf(request.getParameter("id"));
			value = Double.valueOf(request.getParameter("value"));
		} catch (NumberFormatException ex) {
			String errorMessage = LocaleData.getResourceBundle().getString(
					"servlet.error.data.bad");
			request.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return Path.PAGE_ERROR;
		}

		log.trace("Getting current account balance");
		Account account = (Account) DBManager.getInstance().findAccountById(id,
				user);
		account.setBalance(account.getBalance() + value);

		// HERE WE VALIDATE PAYMENT
		// boolean validate(){ return true; }

		log.trace("Updating account balance");
		DBManager.getInstance().updateAccountBalance(account.getBalance(), id);

		request.getSession().setAttribute("account", account);

		request.setAttribute("message", LocaleData.getResourceBundle()
				.getString("servlet.success.account.refill"));
		request.setAttribute("next", Path.COMMAND_VIEW_ACCOUNT);
		String forward = Path.PAGE_SUCCESS;
		log.debug("Command finished");
		return forward;
	}

}
